<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>编辑采购订单</title>
<script type="text/javascript">
    Ext.onReady(function () {
        //是否临时保存
        var temporary = Ext.create('Ext.form.field.Hidden', {
            name: 'temporary',
            value: 0
        });

        var purchaseOrderId = Ext.create('Ext.form.field.Hidden', {
            name: 'id'
        });

        var version = Ext.create('Ext.form.field.Hidden', {
            name: 'lock_version'
        });

        //备注
        var desc = Ext.create('Ext.form.field.Text', {
            fieldLabel: '备注',
            name: 'description',
            anchor: '97%'
        });

        var company = Ext.create('Ext.form.ComboBox', {
            store: companyAllInfoStore,
            fieldLabel: '所属公司',
            allowBlank: false,
            blankText: "所属公司必须选择",
            valueField: 'id',
            displayField: 'name',
            name: 'company_id',//如果不想提交displayField，则在这儿指定要提交的Key，value就是valueField．
            emptyText: '请选择...',
            loadingText: '搜索中...',
            anchor: '95%',
            //pageSize: 10,
            readOnly: true,
            minChars: 0,
            editable: false
        });

        //供应商
        var vendor = Ext.create('Ext.form.ComboBox', {
            store: vendorStore,
            fieldLabel: '供应商',
            allowBlank: false,
            blankText: "供应商必须选择",
            valueField: 'id',
            displayField: 'name',
            name: 'vendor_id',//如果不想提交displayField，则在这儿指定要提交的Key，value就是valueField．
            emptyText: '请选择...',
            loadingText: '搜索中...',
            anchor: '95%',
            //pageSize: 10,
            readOnly: false,
            minChars: 0,
            editable: false
        });

        vendor.on('select', function (combo, record, index) {
            linkman.setValue(record[0].get('linkman'));
            phone.setValue(record[0].get('phone'));
        });


        //要求发货时间
        var actionDate = Ext.create('Ext.form.field.Date', {
            fieldLabel: '到货日期',
            allowBlank: false,
            name: 'action_date',
            format: 'Y-m-d', //格式化日期
            //disabledDays: [0,6],	//不让选择周六，周日
            //disabledDaysText: "周末要休息",
            invalidText: "您输入的日期格式不对，正确格式为2010-01-18",
            blankText: "到货日期必须选择",
            emptyText: '到货日期...',
            anchor: '95%'
        });

        //合同号
        var contractNumber = Ext.create('Ext.form.field.Text', {
            fieldLabel: '合同编号',
            allowBlank: true,
            name: 'contract_number',
            anchor: '95%'
        });

        //联系人
        var linkman = Ext.create('Ext.form.field.Text', {
            fieldLabel: '联系人',
            name: 'linkman',
            anchor: '95%',
            allowBlank: false
        });

        //联系电话
        var phone = Ext.create('Ext.form.field.Text', {
            fieldLabel: '联系电话',
            name: 'phone',
            anchor: '95%',
            allowBlank: false
        });

        //税率
        var taxRate = Ext.create('Ext.form.field.Number', {
            fieldLabel: '税率(%)',
            name: "tax_rate",
            allowBlank: false,
            allowDecimals: true,
            minValue: 0,
            maxValue: 100,
            anchor: '95%'
        });

        var deliveryAddress = Ext.create('Ext.form.field.Text', {
            fieldLabel: '送货地址',
            allowBlank: false,
            name: 'delivery_address',
            anchor: '95%'
        });

        //总金额
        var sumAmount = Ext.create('Ext.form.field.Number', {
            fieldLabel: '总金额',
            name: "amount",
            readOnly: true,
            allowBlank: false,
            allowDecimals: true,
            minValue: 0,
            anchor: '90%'
        });

        //总进项税
        var sumVATAmount = Ext.create('Ext.form.field.Number', {
            fieldLabel: '总税额',
            name: "value_added_tax",
            readOnly: true,
            allowBlank: false,
            allowDecimals: true,
            minValue: 0,
            anchor: '90%'
        });

        //含税总金额
        var sumTaxAmount = Ext.create('Ext.form.field.Number', {
            fieldLabel: '含税总金额',
            name: "tax_amount",
            readOnly: true,
            allowBlank: false,
            allowDecimals: true,
            minValue: 0,
            anchor: '90%'
        });
        //--------------------------------------------------------------------------
        //销售订单CBB
        var saleOrderNumberCBB = Ext.create('Ext.form.ComboBox', {
            store: saleOrderNumberStore,
            fieldLabel: '销售订单单号',
            allowBlank: false,
            blankText: "销售订单必须选择",
            emptyText: '请选择...',
            displayField: 'order_number',
            hideTrigger: false,
            loadingText: '搜索中...',
            anchor: '100%',
            minChars: 0
        });

        saleOrderNumberCBB.on('select', function (combo, record, index) {
            var purchaseOrderItemRecord = purchaseOrderDetailSM.getSelected();
            if (!purchaseOrderItemRecord) {
                return false;
            }
            purchaseOrderItemRecord.reject();
            purchaseOrderItemRecord.set('sale_order_id', records[0].get('id'));
            purchaseOrderItemRecord.set('sale_order_number', records[0].get('order_number'));
        });

        //产品列表
        //产品
        var productCBB = Ext.create('Ext.form.ComboBox', {
            store: productAllInfoStore,
            emptyText: '请选择...',
            displayField: 'name',
            loadingText: '搜索中...',
            anchor: '100%',
            pageSize: 10,
            minChars: 0,
            listConfig: {
                loadingText: 'Searching...',
                getInnerTpl: function () {
                    return '<div style="float:left; width:200px" data-qtip="{name}">{name:ellipsis(18)}</div><div style="float:left; width:110px">{number}</div>{is_suit}';
                }
            }
        });

        productCBB.on('select', function (combo, record, index) {
            var records = purchaseOrderDetailGrid.getSelectionModel().getSelection();
            var purchaseOrderItemRecord = records[0];
            if (!purchaseOrderItemRecord) {
                return false;
            }

            /*if (isDuplicateBySaleOrderProduct(purchaseOrderDetailDS,purchaseOrderItemRecord.get('sale_order_id'),records[0].get('product_id'))){
             //择情删除当前记录
             if (purchaseOrderItemRecord.get('product_id') === record.get('product_id')){
             purchaseOrderItemRecord.set('quantity',records[0].get('quantity'));
             }else{
             purchaseOrderDetailDS.remove(purchaseOrderItemRecord);
             }
             }else{*/
            purchaseOrderItemRecord.set('number', record[0].get('number'));
            purchaseOrderItemRecord.set('spec', record[0].get('spec'));
            purchaseOrderItemRecord.set('unit', record[0].get('unit'));
            purchaseOrderItemRecord.set('unit_price', record[0].get('unit_price'));
            purchaseOrderItemRecord.set('amount', record[0].get('unit_price'));
            purchaseOrderItemRecord.set('quantity', record[0].get('quantity'));
            purchaseOrderItemRecord.set('product_id', record[0].get('id'));
            //判断套装
            purchaseOrderItemRecord.set('is_suit', record[0].get('is_suit'));
            //设置sale_order_detail
            //purchaseOrderItemRecord.set('sale_order_detail_id',records[0].get('id'));
            /*
             Ext.Ajax.request({
             url : '/stock/getProductStockQuantity',
             success : function (result, request) {
             purchaseOrderItemRecord.set('stock_quantity_1',result.responseText.split("|")[0]);
             purchaseOrderItemRecord.set('stock_quantity_2',result.responseText.split("|")[1]);
             if (purchaseOrderItemRecord.get('sale_order_id') != 0){
             //限制即时最大采购数
             Ext.Ajax.request({
             url : '/purchase_order/getProductQuantityForPurchase',
             success : function (result, request) {
             purchaseOrderItemRecord.set('quantity',result.responseText);
             purchaseOrderItemRecord.set('balance_quantity',result.responseText);
             getSumAmount();
             //得到某采购订单已经入库的某产品的数量
             Ext.Ajax.request({
             url : '/purchase_order/getEntryProductQuantityForPurchase',
             success : function (result, request) {
             purchaseOrderItemRecord.set('ed_quantity',result.responseText);
             },
             failure : function (result, request){
             Ext.MessageBox.show({
             title: '消息',
             msg: "通讯失败，请从新操作",
             buttons: Ext.MessageBox.OK,
             icon: Ext.MessageBox.WARNING
             });
             },
             method : 'GET',
             params : {
             purchase_order_id : purchaseOrderId.getValue(),
             sale_order_id : purchaseOrderItemRecord.get('sale_order_id'),
             product_id : record.get('product_id')
             }
             });
             },
             failure : function (result, request){
             Ext.MessageBox.show({
             title: '消息',
             msg: "通讯失败，请从新操作",
             buttons: Ext.MessageBox.OK,
             icon: Ext.MessageBox.WARNING
             });
             },
             method : 'GET',
             params : {
             sale_order_id : purchaseOrderItemRecord.get('sale_order_id'),
             product_id : record.get('product_id')
             }
             });
             } else{
             purchaseOrderItemRecord.set('balance_quantity',1000000);
             }
             },
             failure : function (result, request){
             Ext.MessageBox.show({
             title: '消息',
             msg: "通讯失败，请从新操作",
             buttons: Ext.MessageBox.OK,
             icon: Ext.MessageBox.WARNING
             });
             },
             method : 'GET',
             params : {
             id : record.get('product_id')
             }
             });
             //}*/
        });

        /*productCBB.on('focus', function(combo, record, index) {
         var records = purchaseOrderDetailGrid.getSelectionModel().getSelection();
         productStore.extraParams.id = records[0].get('sale_order_id');
         productStore.load();
         });*/

        //采购订单列表Grid Store
        //销售订单列表Grid Store
        //采购订单列表Grid Store
        Ext.define('PurchaseOrderDetailEditModel', {
            extend: 'Ext.data.Model',
            fields: [
                {name: 'id'},
                {
                    name: 'sale_order_id'
                },
                {
                    name: 'company_id'
                },
                {
                    name: 'sale_order_detail_id'
                },
                {
                    name: 'sale_order_number'
                },
                {
                    name: 'name'
                },
                {
                    name: 'number'
                },
                {
                    name: 'product_name'
                },
                {
                    name: 'spec'
                },
                {
                    name: 'unit'
                },
                {
                    name: 'description'
                },
                {
                    name: 'unit_price',
                    type: 'float'
                },
                {
                    name: 'quantity',
                    type: 'int'
                },
                {
                    name: 'tax_price',
                    type: 'float'
                },
                {
                    name: 'tax_amount',
                    type: 'float'
                },
                {
                    name: 'value_added_tax',
                    type: 'float'
                },
                {
                    name: 'product_id'
                },
                {
                    name: 'amount',
                    type: 'float'
                },
                {
                    name: 'balance_quantity',
                    type: 'int'
                },
                {
                    name: 'ed_quantity',
                    type: 'int'
                },
                {
                    name: 'stock_quantity_1',
                    type: 'int'
                },
                {
                    name: 'stock_quantity_2',
                    type: 'int'
                },
                {
                    name: 'is_suit',
                    convert: function (value, record) {
                        if (value == "1") {
                            return "套装";
                        } else if (value == "0") {
                            return "单品";
                        } else {
                            return value;
                        }
                    }
                }
            ]
        });

        var purchaseOrderDetailDS = Ext.create('Ext.data.Store', {
            autoDestroy: true,
            model: 'PurchaseOrderDetailEditModel',
            proxy: {
                type: 'ajax',
                url: '/purchase_order/getPurchaseOrderDetailsByIdForEdit',
                extraParams: {'purchase_order_id': <%=params[:id]%>},
                reader: {
                    type: 'json',
                    root: 'root',
                    totalProperty: 'totalProperty'// 数据集记录总数
                }
            },
            autoLoad: true
        });

        //生成要订单的产品的Grid
        var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
            clicksToEdit: 1
        });

        //生成要订单的产品的Grid
        var purchaseOrderDetailGrid = Ext.create('Ext.grid.Panel', {
            store: purchaseOrderDetailDS,
            plugins: [cellEditing],
            columns: [Ext.create('Ext.grid.RowNumberer'), {
                header: 'id',
                dataIndex: 'id',
                hidden: true,
                width: 40
            }, {
                header: '销售订单Id',
                dataIndex: 'sale_order_id',
                hidden: true,
                width: 30
            }, {
                header: '销售订单详细Id',
                dataIndex: 'sale_order_detail_id',
                hidden: true,
                width: 30
            }, {
                header: '销售订单',
                dataIndex: 'sale_order_number',
                field: saleOrderNumberCBB,
                hidden: true,
                width: 195
            }, {
                header: '产品名称',
                dataIndex: 'product_name',
                field: productCBB,
                width: 370
            }, {
                header: '产品ID',
                dataIndex: 'product_id',
                width: 50,
                hidden: false
            }, {
                header: '产品编号',
                dataIndex: 'number',
                width: 95
            }, {
                header: '规格',
                dataIndex: 'spec',
                width: 50
            }, {
                header: '单位',
                dataIndex: 'unit',
                width: 50
            }, {
                header: '数量',
                align: 'right',
                dataIndex: 'quantity',
                field: Ext.create('Ext.form.field.Number', {
                    allowBlank: false,
                    allowDecimals: false,
                    minValue: 1
                }),
                align: 'right',
                width: 50
            }, {
                header: '工库',
                dataIndex: 'stock_quantity_1',
                align: 'right',
                hidden: true,
                renderer: stockQuantityRender,
                width: 50
            }, {
                header: '大库',
                dataIndex: 'stock_quantity_2',
                align: 'right',
                hidden: true,
                renderer: stockQuantityRender,
                width: 50
            }, {
                header: '单价',
                dataIndex: 'unit_price',
                renderer: Ext.util.Format.numberRenderer('0,000.0000000000'),
                align: 'right',
                width: 110
            }, {
                header: '金额',
                dataIndex: 'amount',
                renderer: Ext.util.Format.numberRenderer('0,000.00'),
                align: 'right',
                width: 70
            }, {
                header: '含税单价',
                dataIndex: 'tax_price',
                field: Ext.create('Ext.form.field.Number', {
                    allowBlank: false,
                    allowDecimals: true,
                    minValue: 0,
                    decimalPrecision: 2
                }),
                renderer: Ext.util.Format.numberRenderer('0,000.00'),
                align: 'right',
                width: 80
            }, {
                header: '进项税',
                dataIndex: 'value_added_tax',
                renderer: Ext.util.Format.numberRenderer('0,000.00'),
                align: 'right',
                width: 70
            }, {
                header: '含税金额',
                dataIndex: 'tax_amount',
                renderer: Ext.util.Format.numberRenderer('0,000.00'),
                align: 'right',
                width: 80
            }, {
                header: '套装',
                dataIndex: 'is_suit',
                width: 45
            }, {
                header: '备注',
                dataIndex: 'description',
                width: 60,
                field: Ext.create('Ext.form.field.Text', {
                    name: 'description',
                    anchor: '90%'
                })
            }, {
                header: '销售采购差',
                dataIndex: 'balance_quantity',
                width: 90,
                hidden: true
            }, {
                header: '已入库数',
                dataIndex: 'ed_quantity',
                width: 90,
                hidden: true
            }],
            selModel: Ext.create('Ext.selection.CheckboxModel'),
            width: 1170,
            height: 315,
            //frame: true,
            //title: '进货品种列表',
            //frame: true,
            //plugins: checkColumn,

            tbar: [
                {
                    text: '添加产品',
                    iconCls: 'addItem',
                    handler: function () {
                        var record = Ext.ModelManager.create({
                            product_name: '请选择产品',
                            sale_order_id: 0,
                            sale_order_number: '无销售订单关联'
                        }, purchaseOrderDetailGrid.getStore().model);
                        purchaseOrderDetailDS.insert(0, record);
                    }
                },
                {
                    text: '删除',
                    iconCls: 'remove',
                    handler: function () {
                        var records = purchaseOrderDetailGrid.getSelectionModel().getSelection();
                        cellEditing.cancelEdit();
                        purchaseOrderDetailDS.remove(records);
                        getSumAmount();
                    }
                }
            ]
        });

        //暂时保存按钮
        var submitButton = Ext.create('Ext.Button', {
            text: '提交',
            tooltip: '提交采购订单。',
            iconCls: 'icon-save',
            handler: function () {
                if (vendor.getRawValue() === vendor.getValue()) {
                    vendor.reset();
                }
                if (purchaseOrderFormPanel.form.isValid()) {
                    var productsJsonStr = gridStoreToJson(purchaseOrderDetailDS, rejectKeyArray);
                    if (purchaseOrderDetailDS.getCount() == 0 || productsJsonStr === "") {
                        Ext.MessageBox.show({
                            title: '提示',
                            msg: "您还没有选择有效的产品或选择的产品数量为0！",
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.INFO
                        });
                        return;
                    }

                    //检查一下，有没有销售，产品，价格三元素完全相同的记录存在。如果存在就要检查
                    if (isDuplicateForPurchase(purchaseOrderDetailDS)) {
                        Ext.MessageBox.show({
                            title: '消息',
                            msg: "有销售，产品，价格三者完全相同的记录存在，请检查！",
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.INFO
                        });
                        return;
                    }

                    this.disable();
                    var allJsonStr = purchaseOrderFormPanel.getForm().getValues();
                    allJsonStr = Ext.JSON.encode(allJsonStr);
                    allJsonStr = Ext.util.Format.substr(allJsonStr, 0, allJsonStr.length - 1);
                    allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
                    Ext.Ajax.request({
                        url: '/purchase_order/update',
                        success: function (result, request) {
                            if (Ext.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                                Ext.MessageBox.show({
                                    title: '消息',
                                    msg: "保存采购订单，操作成功！",
                                    buttons: Ext.MessageBox.OK,
                                    icon: Ext.MessageBox.INFO
                                });
                            }
                            else {
                                Ext.MessageBox.show({
                                    title: '消息',
                                    msg: Ext.JSON.decode(result.responseText).info,
                                    buttons: Ext.MessageBox.OK,
                                    icon: Ext.MessageBox.WARNING
                                });
                            }
                            editPurchaseOrderWin.destroy();
                        },
                        failure: function (result, request) {
                            Ext.MessageBox.show({
                                title: '消息',
                                msg: "通讯失败，请从新操作",
                                buttons: Ext.MessageBox.OK,
                                icon: Ext.MessageBox.WARNING
                            });
                            editPurchaseOrderWin.destroy();
                        },
                        method: 'POST',
                        params: {
                            data: Ext.JSON.encode(allJsonStr),
                            authenticity_token: authToken.getValue()
                        }
                    });
                }
            }
        });

        //临时保存按钮
        var tempSaveButton = Ext.create('Ext.Button', {
            text: '暂存',
            tooltip: '暂时保存采购订单。',
            iconCls: 'temp-save',
            handler: function () {
                //首先把临时变量设置为1
                temporary.setValue(1);

                if (purchaseOrderFormPanel.form.isValid()) {
                    var productsJsonStr = gridStoreToJson(purchaseOrderDetailDS, rejectKeyArray);
                    if (purchaseOrderDetailDS.getCount() == 0 || productsJsonStr === "") {
                        Ext.MessageBox.show({
                            title: '提示',
                            msg: "您还没有选择有效的产品或选择的产品数量为0！",
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.INFO
                        });
                        return;
                    }

                    //检查一下，有没有销售，产品，价格三元素完全相同的记录存在。如果存在就要检查
                    if (isDuplicateForPurchase(purchaseOrderDetailDS)) {
                        Ext.MessageBox.show({
                            title: '消息',
                            msg: "有销售，产品，价格三者完全相同的记录存在，请检查！",
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.INFO
                        });
                        return;
                    }

                    this.disable();
                    var allJsonStr = purchaseOrderFormPanel.getForm().getValues();
                    allJsonStr = Ext.JSON.encode(allJsonStr);
                    allJsonStr = Ext.util.Format.substr(allJsonStr, 0, allJsonStr.length - 1);
                    allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";

                    Ext.Ajax.request({
                        url: '/purchase_order/update',
                        success: function (result, request) {
                            if (Ext.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                                Ext.MessageBox.show({
                                    title: '消息',
                                    msg: "暂存采购订单，操作成功！",
                                    buttons: Ext.MessageBox.OK,
                                    icon: Ext.MessageBox.INFO
                                });
                            }
                            else {
                                Ext.MessageBox.show({
                                    title: '消息',
                                    msg: Ext.JSON.decode(result.responseText).info,
                                    buttons: Ext.MessageBox.OK,
                                    icon: Ext.MessageBox.WARNING
                                });
                            }
                            editPurchaseOrderWin.destroy();
                        },
                        failure: function (result, request) {
                            Ext.MessageBox.show({
                                title: '消息',
                                msg: "通讯失败，请联系管理员！",
                                buttons: Ext.MessageBox.OK,
                                icon: Ext.MessageBox.WARNING
                            });
                            editPurchaseOrderWin.destroy();
                        },
                        method: 'POST',
                        params: {
                            data: Ext.JSON.encode(allJsonStr),
                            authenticity_token: authToken.getValue()
                        }
                    });
                }
            }
        });
        tempSaveButton.disable();
        //暂时保存按钮
        var closeButton = Ext.create('Ext.Button', {
            text: '关闭',
            tooltip: '关闭当前窗口，并且当前编辑的信息不能保存。',
            iconCls: 'exit',
            handler: function () {
                editPurchaseOrderWin.destroy();
            }
        });

        //采购申请的FormPanel
        var purchaseOrderFormPanel = Ext.create('Ext.form.Panel', {
            fieldDefaults: {
                labelWidth: 65,
                labelAlign: 'right'
            },
            width: 1183,
            frame: true,
            url: '/purchase_order/update',
            method: 'GET',
            reader: Ext.create('Ext.data.reader.Json', {
                model: 'PurchaseOrderModel',
                root: 'root'
            }),
            /*reader: new Ext.data.JsonReader({
             root: 'root'
             }, [{
             name: 'id'
             }, {
             name: 'vendor_id'
             }, {
             name: 'amount'
             }, {
             name: 'value_added_tax'
             }, {
             name: 'tax_amount'
             }, {
             name: 'description'
             }, {
             name: 'action_date',
             type: 'date',
             dateFormat: 'Y/m/d'
             }, {
             name: 'contract_number'
             }, {
             name: 'linkman'
             }, {
             name: 'phone'
             }, {
             name: 'tax_rate'
             }, {
             name: 'delivery_address'
             },{
             name: 'lock_version'
             }]),*/
            //defaultType: 'textfield',
            items: [
                {
                    layout: 'column',
                    xtype: 'container',
                    items: [
                        {
                            columnWidth: .2,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [company]
                        },{
                            columnWidth: .25,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [vendor]
                        },
                        {
                            columnWidth: .17,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [actionDate]
                        },
                        {
                            columnWidth: .17,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [contractNumber]
                        },
                        {
                            columnWidth: .16,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [taxRate]
                        }
                    ]
                },
                {
                    layout: 'column',
                    xtype: 'container',
                    items: [
                        {
                            columnWidth: .2,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [linkman]
                        },
                        {
                            columnWidth: .25,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [phone]
                        },
                        {
                            columnWidth: .55,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [deliveryAddress]
                        }
                    ]
                },
                {
                    layout: 'column',
                    xtype: 'container',
                    items: [
                        {
                            columnWidth: 1,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [desc]
                        }
                    ]
                },
                {
                    layout: 'column',
                    xtype: 'container',
                    items: [
                        {
                            columnWidth: 1,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [purchaseOrderDetailGrid]
                        }
                    ]
                },
                {
                    layout: 'column',
                    xtype: 'container',
                    items: [
                        {
                            columnWidth: 0.25,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [sumAmount]
                        },
                        {
                            columnWidth: 0.25,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [sumVATAmount]
                        },
                        {
                            columnWidth: 0.25,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [sumTaxAmount]
                        }
                    ]
                },
                purchaseOrderId,
                temporary,
                version
            ],
            buttons: [submitButton, tempSaveButton, closeButton]
        });

        purchaseOrderFormPanel.form.load({
            url: '/purchase_order/getPurchaseOrderById?id=' + <%=params[:id]%>,
            method: 'GET',
            waitMsg: '正在载入数据...',
            success: function (form, action) {
                var respJson = Ext.JSON.decode(action.response.responseText);
                vendor.setRawValue(respJson.root[0].vendor.name);
            },
            failure: function (form, action) {
                Ext.MessageBox.show({
                    title: '消息',
                    msg: "信息加载失败！",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                });
                editPurchaseOrderWin.destroy();
            }
        });

        purchaseOrderFormPanel.render('edit_purchase_order');
        //
        purchaseOrderDetailGrid.on('edit', afterEdit, this);

        function afterEdit(editor, obj, options) {
            // execute an XHR to send/commit data to the server, in callback do (if successful):
            if (obj.field == "product_name" || obj.field == "quantity" || obj.field == "tax_price") {
                /*if (obj.record.get('quantity') > obj.record.get('balance_quantity')){
                 obj.record.set('quantity',obj.record.get('balance_quantity'));
                 }*/
                if (obj.record.get('quantity') > 0) {
                    //设置含税单价和含税竞价
                    obj.record.set('unit_price', Math.round(10000000000 * obj.record.get('tax_price') / (1 + taxRate.getValue() * 0.01)) / 10000000000);
                    obj.record.set('tax_amount', obj.record.get('tax_price') * obj.record.get('quantity'));
                    obj.record.set('amount', Math.round(obj.record.get('quantity') * 100 * obj.record.get('unit_price')) / 100);
                    obj.record.set('value_added_tax', Math.round(obj.record.get('amount') * taxRate.getValue() * 0.01 * 1000) / 1000);
                } else {
                    obj.record.set('amount', 0);
                }
            }
            getSumAmount();
        }

        function getSumAmount() {
            sumAmount.setValue(0);
            sumVATAmount.setValue(0);
            sumTaxAmount.setValue(0);
            var records = purchaseOrderDetailDS.getRange(0, purchaseOrderDetailDS.getCount());
            for (var i = 0; i < records.length; i++) {
                var record = records[i];
                var quantity = record.get('quantity');
                var unitPrice = record.get('unit_price');
                var taxPrice = record.get('tax_price');
                //record.set('amount',quantity*unitPrice);
                //record.set('tax_amount',quantity*taxPrice);
                //var amount = record.get('amount');
                sumAmount.setValue(sumAmount.getValue() + record.get('amount'));
                sumVATAmount.setValue(sumVATAmount.getValue() + record.get('value_added_tax'));
                sumTaxAmount.setValue(sumTaxAmount.getValue() + record.get('tax_amount'));
            }
        }
    })
</script>
</head>
<body>
<div id="edit_purchase_order"></div>
</body>
</html>